import { Music } from '@/modules/Music';
import { RootState } from '@/modules/RootState';
import { getMusicUrl } from '@/utils/api';
import { Message } from 'element-react';
import React, { createContext, useCallback, useContext, useEffect, useRef, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux';

interface AudioContextProps{
  audioDuration:number,
  audioCurrent:number,
  volume:number,
  audioPlay:boolean,
  audioId:number,
  audioIndex:number,
  // playMusic:({payload,index}:{payload:Music[],index:number})=>void,
  playMusic:({payload,index}:{payload:Music[],index:number})=>void
  StartOrStop:()=>void,
  nextSong:(num:number)=>void
}

export const AudioContext = createContext<AudioContextProps>({
  audioDuration:0,
  audioCurrent:0,
  volume:0,
  audioPlay:false,
  audioId:-1,
  audioIndex:0,
  playMusic:()=>{},
  StartOrStop:()=>{},
  nextSong:()=>{}
});


export const AudioProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const musicList = useSelector((state:RootState) => state.musicList);
  const dispatch = useDispatch()
  const [audioDuration,setAudioDuration] = useState(0)/* 音乐对象时间总长 */
  const [audioCurrent,setAudioCurrent] = useState(0)/* 音乐当前播放时长 */
  const [volume, setVolume] = useState(0);/* 音量大小 */
  const [audioPlay,setAudioPlay] = useState(false);/* 音乐暂停与开始 */
  const [audioId,setAudioId] = useState(-1)/* 音乐序号 */
  const [audioIndex,setAudioIndex] = useState(-1)/* 音乐的第几个 */

  const audioRef = useRef<HTMLAudioElement>(null);

  const playMusic = useCallback(({payload,index}:{payload:Music[],index:number})=>{
    console.log(payload)
    if(!payload){
      return error('网络出错了')
    }
    let res = payload[0]
    // console.log(payload)
    // console.log(index)
    if(!audioRef.current) return
    if(payload){
      audioRef.current.src = res.url
      audioRef.current.volume = 10/100
      audioRef.current.play().then(()=>{
        setAudioDuration(res.time)/* 时间总长 */
        setAudioPlay(true)/* 音乐开始状态 */
        setAudioId(res.id)/* 音乐序号 */
        setAudioIndex(index)/* 音乐第几个 */
        setAudioCurrent(0)
      }).catch(err=>{
        console.log(err)
      })
    }else{
      error('网络出错了')
    }
  },[audioId,audioIndex,audioDuration,audioPlay])

  const StartOrStop = useCallback(()=>{
    if(audioId == -1 || null){
      return error('暂无歌曲哦')
    }
    if(!audioRef.current) return
    if(audioPlay){
      audioRef.current.pause()
    }else{
      audioRef.current.play()
    }
    setAudioPlay(!audioPlay)
  },[audioPlay])

  const nextSong = useCallback(async (num:number)=>{
    let newIndex = audioIndex + num
    if(audioId == -1){
      return error('暂无歌曲哦')
    }
    if(newIndex < 0){
      return error('已经是第一首了哦')
    }
    let res =await (dispatch as any)(getMusicUrl(musicList.songs[newIndex].id))
    const keys = {
      payload:res.payload,
      index:newIndex
    }
    playMusic(keys)
  },[audioIndex,audioPlay,audioId])

  useEffect(() => {
    const audioElement = audioRef.current;

    const handleTimeUpdate = () => {
      if (audioElement) {
        setAudioCurrent(audioElement.currentTime) ;
        console.log('Current Time:', audioRef.current);
      }
    };

    if (audioElement) {
      audioElement.addEventListener('timeupdate', handleTimeUpdate);
    }

    return () => {
      if (audioElement) {
        audioElement.removeEventListener('timeupdate', handleTimeUpdate);
      }
    };
  }, []);

  useEffect(()=>{
    // console.log(audioIndex)
  },[audioIndex])

  return (
    <AudioContext.Provider
      value={{
        audioDuration,
        audioCurrent,
        volume,
        audioPlay,
        audioId,
        audioIndex,
        playMusic,
        StartOrStop,
        nextSong
      }}
    >
      {children}
      <audio ref={audioRef}/>
    </AudioContext.Provider>
  );
};
export default Audio

export function useAudioContext(){
  return useContext(AudioContext)
}

const error = (item:string)=>{
  Message({
    message: item,
    type: 'error'
  });
}